import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {ThemeableBrowser, ThemeableBrowserObject, ThemeableBrowserOptions} from "@ionic-native/themeable-browser";
import {StreamingMedia, StreamingVideoOptions} from "@ionic-native/streaming-media";
import {FileTransfer, FileTransferObject} from '@ionic-native/file-transfer';
import {File} from "@ionic-native/file";
import {Platform} from "ionic-angular";
import {FileOpener} from "@ionic-native/file-opener";

/*
  Generated class for the SourceViewProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/

@Injectable()
export class SourceViewProvider {
  constructor(public http: HttpClient,public themeBrowser:ThemeableBrowser,private streamingMedia: StreamingMedia,private transfer: FileTransfer,private file:File,
              public platform: Platform,private fileOpener: FileOpener) {
  }
  /**
   * 显示相应资源内容页面（图片，案例，网页链接等用浏览器打开的资源）
   * @param path
   * @param title
   * @returns {ThemeableBrowserObject}
   */
  showPage(path,title):ThemeableBrowserObject{
    let optionsTheme:ThemeableBrowserOptions={
      statusbar: {
        color: '#ffffffff'
      },
      toolbar: {
        height: 50,
        color: '#cc0000'
      },
      title: {
        color: '#ffffffff',
        staticText:title,
        showPageTitle: true
      },
      backButton: {
        wwwImage: 'assets/imgs/back.png',
        wwwImagePressed: 'assets/imgs/back.png',
        wwwImageDensity: 2,
        align: 'left',
        event: 'backPressed'
      },
      closeButton: {
        wwwImage: 'assets/imgs/close.png',
        wwwImagePressed: 'assets/imgs/close.png',
        imagePressed: 'close_pressed',
        align: 'right',
        event: 'closePressed'
      },
      backButtonCanClose: true
    }

    let browser=this.themeBrowser.create(path,'_blank',optionsTheme);

    return browser;
  }

  /**
   * 显示视频、音频播放页面
   * @param url
   */
  showVideo(url)
  {
    let options: StreamingVideoOptions = {
      successCallback: () => { console.log('Video played') },
      errorCallback: (e) => { console.log('Error streaming') },
      orientation: 'landscape'
    };

    this.streamingMedia.playVideo(url, options);
  }

  /**
   * 资源下载(下载完成后打开文件)
   * @param url:源路径
   * @param path:目标文件相对路径
   * @param type 0：下载后直接打开，1：仅下载
   */
  download(url,path,type) {
    const fileTransfer: FileTransferObject = this.transfer.create();
    fileTransfer.download(url, this.getTargetPath() + path).then((entry) => {
      if(type==0)
      {
        this.openFile(path);
      }
    }).catch((error)=>
    {
    });
  }

  /**
   * @param 资源相对路径
   * 打开本地资源
   */
  openFile(path)
  {
    this.fileOpener.open(this.getTargetPath()+path, this.getFileMimeType(this.getFileType(this.getTargetPath()+path)))
      .then(() => {
      })
      .catch(() => {
      });
  }

  /**
   * 获取文档类型
   * @param {string} fileName
   * @returns {string}
   */
  getFileType(fileName: string): string {
    return fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase();
  }

  /**
   * 获取文件MimeType
   * @param {string} fileType
   * @returns {string}
   */
  getFileMimeType(fileType: string): string {
    let mimeType: string = '';

    switch (fileType) {
      case 'txt':
        mimeType = 'text/plain';
        break;
      case 'docx':
        mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        break;
      case 'doc':
        mimeType = 'application/msword';
        break;
      case 'pptx':
        mimeType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        break;
      case 'ppt':
        mimeType = 'application/vnd.ms-powerpoint';
        break;
      case 'xlsx':
        mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        break;
      case 'xls':
        mimeType = 'application/vnd.ms-excel';
        break;
      case 'zip':
        mimeType = 'application/x-zip-compressed';
        break;
      case 'rar':
        mimeType = 'application/octet-stream';
        break;
      case 'pdf':
        mimeType = 'application/pdf';
        break;
      case 'jpg':
        mimeType = 'image/jpeg';
        break;
      case 'png':
        mimeType = 'image/png';
        break;
      default:
        mimeType = 'application/' + fileType;
        break;
    }
    return mimeType;
  }

  /**
   * 获取目标文件路径父级路径
   * 安卓6及其以下版本父级路径file:///storage/sdcard0/Download/，6以上版本父级路径this.file.dataDirectory
   */
  getTargetPath()
  {
    let targetPath;
    if(this.platform.is("android"))
    {
      if(+this.platform.versions()["android"]["str"].split('.')[0]<=6)
      {
        targetPath="file:///storage/sdcard0/Download/";
      }
      else
      {
        targetPath=this.file.dataDirectory
      }
    }
    else if(this.platform.is("ios"))
    {
      targetPath=this.file.dataDirectory
    }
    return targetPath;
  }
}
